<?php

namespace app\admin\controller;

use app\models\{Region, Applyagent, GarbageCate, CateSons, AreaPrice};
use think\Controller;
use think\facade\Env;
use think\Db;
use oss\Oss;
use app\facade\Redis;

class Base extends Controller
{

    public function getmessage()
    {
        $name = 'messagelist_' . $this->request->admin['id'];
        $length = Redis::lLen($name);
        // 遍历 list
        $lists = Redis::lRange($name, 0, $length - 1);
        if (!empty($lists)) {
            Redis::del($name);
            return json(['code' => 0, 'status' => 0, 'msg' => '获取成功']);
        }
        return json(['code' => 1, 'status' => 1, 'msg' => '不存在可通知']);
    }

    public function region_update()
    {
        $code = $this->request->post('id/d', 0); //关键词
        $data = array(
            'id' => $code,
            'key' => '2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT'
        );
        $result = api_curl('https://apis.map.qq.com/ws/district/v1/getchildren', $data, 0);
        $result = json_decode($result, true);
        $area_code = Region::where(['area_code' => $code, 'level' => 3])->find();
        if (empty($area_code)) {
            return json(['code' => 1, 'status' => 1, 'msg' => '编码不存在']);
        }
        if (!empty($result['result'][0])) {
            foreach ($result['result'][0] as $result_son) {
                $have = Region::where(['area_code' => $code, 'level' => 4, 'code' => $result_son['id']])->find();
                if (empty($have)) {
                    $arr = [
                        'parent_id' => $area_code['id'],
                        'level' => 4,
                        'area_code' => $code,
                        'name' => $result_son['fullname'],
                        'code' => $result_son['id']
                    ];
                    Db::startTrans();
                    try {
                        (new Region())->save($arr);
                        Db::commit();
                    } catch (\Exception $e) {
                        return json(['code' => 1, 'status' => 1, 'mag' => $e->getMessage()]);
                        Db::rollback();
                    }
                }
            }
        } else {
            return json(['code' => 1, 'status' => 1, 'msg' => '请求失败']);
        }
        return json(['code' => 0, 'status' => 0, 'msg' => '更新成功']);
    }

    public function getaddress()
    {
        $keyword = $this->request->get('keyword/s', ''); //关键词
        $url = 'https://apis.map.qq.com/ws/place/v1/suggestion';
        $url = $url . "?keyword=" . $keyword  . '&key=2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT';
        $result = getData($url);
        if (!empty($result) && $result['status'] == 0) {
            return json(['code' => 0, 'count' => $result['count'], 'data' => $result['data']]);
        }
        return json(['code' => 0, 'count' => 0, 'data' => []]);
    }


    public function getlatlon($lat = 0, $lon = 0)
    {
        $lat = $this->request->get('lat/f', '0'); //关键词
        $lon = $this->request->get('lon/f', '0'); //关键词
        $url = 'https://apis.map.qq.com/ws/geocoder/v1';
        $url = $url . "?location=" . $lat . ',' . $lon . '&key=2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT&poi_options=radius=50;policy=5';
        $result = getData($url);
        if (!empty($result) && $result['status'] == 0) {
            $street_id = (new Region())
                ->where(['level' => 4])
                ->where('area_code', 'like', '%' . $result['result']['ad_info']['adcode'] . '%')
                ->where('name|remark', 'like', '%' . $result['result']['address_reference']['town']['title'] . '%')->value('id');
            $result['result']['ad_info']['street'] = $street_id ?? 0;
            return json(['code' => 0, 'data' => $result['result']]);
        }
        return json(['code' => 0, 'data' => []]);
    }

    public function initialize()
    {
        $menu = config('menu.menu');
        $controller = strtolower($this->request->controller());
        $action = strtolower($this->request->action());
        $path = [];
        if (isset($menu[$controller])) {
            $path['c'] = $menu[$controller]['name'] ?: null;
            $path['a'] = $menu[$controller]['sub'][$action]['name'] ?: null;
            $path['s'] = $menu[$controller]['sub'][$action]['show'] ?: null;
        }
        $this->assign('path', $path);
    }

    protected function get_rand_str($len = 6)
    {
        $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'), array('$', '@', '#', '%', '&'));
        shuffle($arr);
        $sub_arr = array_slice($arr, 0, $len);
        return implode('', $sub_arr);
    }

    public function upload_img()
    {
        if ($this->request->isPost()) {
            $file = request()->file('file');
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
            $info = $file->validate(['size' => 1024 * 1024 * 5, 'ext' => 'jpg,png,gif,jpeg'])
                ->move($path);
            if (!$info) {
                return json(['code' => 1, 'status' => 1, 'data' => []]);

                $this->result([], 1, $file->getError());
            } else {
                $url = '/uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                $url = url($url, '', '', true);
                return json(['code' => 0, 'status' => 0, 'data' => ['src' => $url]]);
            }
        }
    }

    public function getarea()
    {
        $id = $this->request->get('id/d', 0);
        $adminid = $this->request->get('adminid/d', 0);
        $level = $this->request->get('level/d', 0);
        $admin = $this->request->admin;
        if ($adminid > 0) {
            $data = Db::table('tb_admin')->where('id', $adminid)->find();
            if (!empty($data)) {
                $admin['province'] = $data['province'];
                $admin['city'] = $data['city'];
                $admin['area'] = $data['area'];
                $admin['street'] = $data['street'];
                $admin['type'] = $data['type'];
            }
        }
        if (empty($id)) {
            if ($level == 1) {
                $list = (new Region())->where('level', $level)->field('area_code,name')->select();
            }
            if ($level == 2) {
                $area = (new Region())->where('area_code', $admin['city'])->value('parent_id');
                if (empty($area)) {
                    return json(['code' => 0, 'status' => 0, 'data' => []]);
                }
                $list = (new Region())->where('parent_id', $area)->where('level', $level)->field('area_code,name')->select();
            }
            if ($level == 3) {
                if (empty($admin['area'])) {
                    $area = (new Region())->where('area_code', $admin['city'])->value('id');
                    if (empty($area)) {
                        return json(['code' => 0, 'status' => 0, 'data' => []]);
                    }
                    $list = (new Region())->where('parent_id', $area)->where('level', $level)->field('area_code,name')->select();
                } else {
                    $area = (new Region())->where('area_code', $admin['area'])->value('parent_id');
                    if (empty($area)) {
                        return json(['code' => 0, 'status' => 0, 'data' => []]);
                    }
                    $list = (new Region())->where('parent_id', $area)->where('level', $level)->field('area_code,name')->select();
                }
            }
            if ($level == 4) {
                if (empty($admin['street'])) {
                    $area = (new Region())->where('area_code', $admin['area'])->value('id');
                    if (empty($area)) {
                        return json(['code' => 0, 'status' => 0, 'data' => []]);
                    }
                    $list = (new Region())->where('parent_id', $area)->where('level', $level)->field('id,area_code,name')->select();
                } else {
                    $area = (new Region())->where('id', $admin['street'])->value('parent_id');
                    if (empty($area)) {
                        return json(['code' => 0, 'status' => 0, 'data' => []]);
                    }
                    $list = (new Region())->where('parent_id', $area)->where('level', $level)->field('id,area_code,name')->select();
                }
            }
        } else {
            $area = (new Region())->where('level', ($level - 1))->where('area_code', $id)->value('id');
            if (empty($area)) {
                return json(['code' => 0, 'status' => 0, 'data' => []]);
            }
            $list = (new Region())->where('parent_id', $area)->field('id,area_code,name')->select();
        }
        return json(['code' => 0, 'status' => 0, 'data' => $list, 'province' => $admin['province'], 'city' => $admin['city'], 'street' => $admin['street'], 'area' => $admin['area'], 'type' => $admin['type']]);
    }

    public function getcate()
    {
        $list = (new GarbageCate())->field('id,name')->select();
        return json(['code' => 0, 'status' => 0, 'data' => $list]);
    }

    public function getcateson()
    {
        $id = $this->request->get('id/d', 0);
        $admin = $this->request->admin; //管理员信息
        $admin['area'] = explode(',', $admin['area']);
        $admin['street'] = explode(',', $admin['street']);
        $admin['province'] = [$admin['province'], 0];
        $admin['city'] = [$admin['city'], 0];
        $admin['area'][] = 0;
        $admin['street'][] = 0;
        if ($admin['type'] == 1) {
            $list = (new CateSons());
        } elseif ($admin['type'] == 2) {
            $list = (new CateSons())->where(['provinceid' => $admin['province'], 'cityid' =>  $admin['city'], 'areaid' =>  $admin['area']]);
        } else {
            $list = (new CateSons())->where(['provinceid' => $admin['province'], 'cityid' =>  $admin['city'], 'areaid' =>  $admin['area'], 'streetid' =>  $admin['street']]);
        }
        $list = $list->where('cate', $id)->field('id,name,provinceid,cityid,areaid,streetid')->select();
        foreach ($list as $lists) {
            $street = (new Region())->where(['id' => $lists['streetid'], 'level' => 4])->find();
            $area = (new Region())->where(['area_code' => $lists['areaid'], 'level' => 3])->find();
            $city = (new Region())->where(['area_code' => $lists['cityid'], 'level' => 2])->find();
            $province = (new Region())->where(['area_code' => $lists['provinceid'], 'level' => 1])->find();
            $lists['street_text'] = $street['name'] ?? '';
            $lists['area_text'] = $area['name'] ?? '';
            $lists['city_text'] = $city['name'] ?? '';
            $lists['province_text'] = $province['name'] ?? '';
        }
        return json(['code' => 0, 'status' => 0, 'data' => $list]);
    }

    public function getsons()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new CateSons())->where('id', $id)->find();
        return json(['code' => 0, 'status' => 0, 'data' => $list]);
    }

    public function getarea2()
    {
        $id = $this->request->get('id/d', 0); //区域ID
        $adminid = $this->request->get('adminid/d', 0); //管理员ID
        $level = $this->request->get('level/d', 0); //行政等级
        if ($adminid > 0) {
            $admin = Db::table('tb_admin')->where('id', $adminid)->find();
        } else {
            $admin = $this->request->admin; //管理员信息
        }
        $admin['area'] = explode(',', $admin['area']);
        $admin['street'] = explode(',', $admin['street']);
        if ($id > 0) {
            if ($level == 1) {
                $list = (new Region())->where(['level' => $level])->select();
            }
            if ($level == 2) {
                $parent_id = (new Region())->where(['area_code' => $id, 'level' => ($level - 1)])->value('id');
                $list = (new Region())->where(['parent_id' => $parent_id])->select();
            }
            if ($level == 3) {
                $parent_id = (new Region())->where(['area_code' => $id, 'level' => ($level - 1)])->value('id');
                $list = (new Region())->where(['parent_id' => $parent_id])->select();
            }
            if ($level == 4) {
                $parent_id = (new Region())->where(['area_code' => $id, 'level' => ($level - 1)])->value('id');
                $list = (new Region())->where(['parent_id' => $parent_id])->select();
            }
        } else {
            if ($level == 1) {
                $list = (new Region())->where(['level' => $level])->select();
            }
            if ($level == 2) {
                $parent_id = (new Region())->where(['area_code' => $admin['province'], 'level' => ($level - 1)])->value('id');
                $list = (new Region())->where(['parent_id' => $parent_id])->select();
            }
            if ($level == 3) {
                $parent_id = (new Region())->where(['area_code' => $admin['city'], 'level' => ($level - 1)])->value('id');
                $list = (new Region())->where(['parent_id' => $parent_id])->select();
            }
            if ($level == 4) {
                $parent_id = (new Region())->where(['area_code' => $admin['area'], 'level' => ($level - 1)])->value('id');
                $list = (new Region())->where(['parent_id' => $parent_id])->select();
            }
        }
        return json(['code' => 0, 'status' => 0, 'data' => $list, 'province' => $admin['province'], 'city' => $admin['city'], 'street' => $admin['street'], 'area' => $admin['area'], 'type' => $admin['type']]);
    }

    public function price()
    {
        $id = $this->request->get('id/d', 0); //街道ID
        $area = (new Region())->where(['id' => $id, 'level' => 4])->value('area_code'); //区域ID
        $where = [
            'areaid' => $area,
            'streetid' => 0
        ];
        $where1 = [
            'areaid' => $area,
            'streetid' => $id
        ];
        $list = (new AreaPrice())->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query1) use ($where1) {
            $query1->where($where1);
        })->select();
        foreach ($list as $lists) {
            $lists['name'] = (new CateSons())->where('id', $lists['catsonsid'])->value('name');
        }
        return json(['code' => 0, 'status' => 0, 'data' => $list]);
    }
}
